package exercises.day02.pt03;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
import java.util.*;

/**
 *
 * @author (jaice) may 29, 2012
 *
 *
 * c. Create an application which will display the number of words and the
 * frequency from Joyce Kilmer's poem. Arrange the list in the descending order
 * of word frequency.
 *
 */
public class WordFrequency {

    private String poem = "I think that I shall never see A poem lovely as a tree A tree whose hungry mouth is prest Against the sweet earth's flowing breast "
            + "A tree that looks at God all day And lifts her leafy arms to pray A tree that may in summer wear A nest of robins in her hair Upon whose bosom snow has lain "
            + "Who intimately lives with rain Poems are made by fools like me But only God can make a tree";
    private String splitWords[];
    private String word;
    private int count = 0;

    public WordFrequency(String words, int count) {
        this.word = words;
        this.count = count;


    }

    public WordFrequency() {
    }

    public int getCount() {
        return this.count;
    }

    public String getWord() {
        return this.word;
    }

    public void split() {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        //   HashMap< Integer, String> sorted_map = new HashMap< Integer, String>();


        poem.toLowerCase();
        splitWords = poem.split(" ");
        //convert lower case to all and add to database
        for (String s : splitWords) {
            Integer currValue = map.get(s.toLowerCase().trim());

            //if does not exits, add to collection
            if (currValue == null) {
                map.put(s.toLowerCase().trim(), 1);

            } else {//add +1 to word
                map.put(s.toLowerCase().trim(), currValue + 1);

            }
        }

        //first get the set of key values
        Set<String> keys = map.keySet();
        ArrayList<WordFrequency> list = new ArrayList<WordFrequency>();


        for (String key : keys) {
            WordFrequency add = new WordFrequency(key.toString(), map.get(key));
            list.add(add);


        }


        ArrayList< WordFrequency> sorted;

        sorted = list;



        Collections.sort(sorted, new Comparator<WordFrequency>() {

            @Override
            public int compare(WordFrequency s1, WordFrequency s2) {

                return Integer.toString(s2.getCount()).compareToIgnoreCase(Integer.toString(s1.getCount()));


            }
        });



        for (WordFrequency wf : sorted) {

            System.out.println(wf.getCount() + " " + wf.getWord());
        }




    }

    public static void main(String args[]) {
        //instantiate
        WordFrequency wf = new WordFrequency();
        //split and count
        wf.split();

    }
}
